package com.example.androidlearning.sy11;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.androidlearning.R;

import java.util.ArrayList;

public class Sy1101_ContentProvider extends AppCompatActivity {

    Cursor cursor;
    Button[] button;
    TextView textView;
    AlertDialog.Builder ab;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sy1101_main);

        init();

    }

    void init(){
        textView = findViewById(R.id.sy11_text);
        final EditText editText = new EditText(getContext());
        ab = new AlertDialog.Builder(getContext());
        ab.setTitle("输入联系人");
        ab.setView(editText);

        button = new Button[3];
        button[0] = findViewById(R.id.sy11_getcontact);
        button[1] = findViewById(R.id.sy11_getbyphone);
        button[2] = findViewById(R.id.sy11_addcontact);
        button[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("显示结果\n");
                getContacts();
            }
        });
        button[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ab.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(!editText.getText().equals("")){
                            textView.setText("显示结果\n");
                            queryContact(editText.getText().toString());
                        }

                        ((ViewGroup)editText.getParent()).removeView(editText);
                        dialog.dismiss();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        ((ViewGroup)editText.getParent()).removeView(editText);
                        dialog.dismiss();
                    }
                });
                ab.show();

            }
        });
        button[2].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    addContact();
                } catch (RemoteException | OperationApplicationException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void getContacts(){
        //查询获取联系人的id
        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        //查询
        cursor = resolver.query(uri, null, null, null, null);
        while (cursor.moveToNext()){
            textView.append("联系人：");
            textView.append(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            textView.append("电话：");
            textView.append(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            textView.append("\n");
        }
        cursor.close();
    }

    private void queryContact(String number){
        System.out.println(number);
        Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number);
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data.DISPLAY_NAME}, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            textView.append("联系人：");
            textView.append(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            cursor.close();
        }else {
            Toast.makeText(getApplicationContext(), "找不到" + number, Toast.LENGTH_SHORT).show();
        }
    }

    private void addContact() throws RemoteException, OperationApplicationException{

        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");

        ContentResolver resolver = getContentResolver();
        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
                .withValue("account_name", null)
                .build();
        operations.add(op1);

        ContentProviderOperation op2 = ContentProviderOperation.newInsert(dataUri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/name")
                .withValue("data2", "Coder-pig")
                .build();
        operations.add(op2);

//        ContentProviderOperation op3 = ContentProviderOperation.newInsert(dataUri)
//                .withValueBackReference("raw_contact", 0)
//                .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
//                .withValue("data1", "18078469412")
//                .withValue("data2", "2")
//                .build();
//        operations.add(op3);
//
//        ContentProviderOperation op4 = ContentProviderOperation.newInsert(dataUri)
//                .withValueBackReference("raw_contact", 0)
//                .withValue("mimetype", "vnd.android.cursor.item/email_v2")
//                .withValue("data1", "18078469412@qq.com")
//                .withValue("data2", "2")
//                .build();
//        operations.add(op4);

        resolver.applyBatch("com.android.contacts", operations);
        Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();

    }

    private Context getContext(){
        return this;
    }
//    private ContentProviderOperation

}
